﻿using System;
using System.Linq;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Mappers;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsCreateUpdateUserAndAssignGroupsDataCommand : CmsCreateUpdateUserCommand
    {
        public override IQueryable<CmsUserInformation> Execute()
        {
            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsUserInformation>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsUserInformation>;

            if (currentUnitOfWork != null)
            {
                if (CommandParameter.Id > 0)
                {
                    SqlUtility<CmsUserInformation, int>.ExecuteNonQuery(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_UpdateUser",
                        CommandParameter,
                        new CmsUserInformationAllForManagementDataMapper());
                }
                else
                {
                    CommandParameter.Id = SqlUtility<CmsUserInformation, int>.ExecuteNonQuery(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_CreateUser",
                        CommandParameter,
                        new CmsUserInformationAllForManagementDataMapper(),
                        true);
                }
            }

            return null;
        }
    }
}
